package com.foreknow.protals.controller;

import com.foreknow.protals.common.api.CommonResult;
import com.foreknow.protals.dto.UmsAdminLoginDto;
import com.foreknow.protals.mbg.model.UmsAdmin;
import com.foreknow.protals.service.UmsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@Api(tags = "UmsAdminController",description = "用户管理")
@RequestMapping("/admin")
public class UmsAdminController {
    @Autowired
    private UmsAdminService umsAdminService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("用户注册")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsAdmin> register(UmsAdmin umsAdminDto) {
        UmsAdmin admin = umsAdminService.register(umsAdminDto);
        if(admin == null) {
            CommonResult.failed("");
        }
        return CommonResult.success(admin);
    }

    @ApiOperation("用户登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestBody UmsAdminLoginDto umsAdminLoginDto) {
        //调用service中登录的方法返回一个token
        String token = umsAdminService.login(umsAdminLoginDto.getUsername(),umsAdminLoginDto.getPassword());
        //判断token是否为空，如果为空提示错误信息
        if(token == null) {
            return CommonResult.failed("用户名或密码错误");
        }
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return CommonResult.success(map);
    }

}
